import importlib, os, re

class Plugin:
    __slots__ = ('module', 'name', 'usage')

    def __init__(self, module, name='', usage=''):
        self.module = module
        self.name = name
        self.usage = usage

def load_plugin(bot, module_name):
    try:
        module = importlib.import_module(module_name)
        name = getattr(module, '__plugin_name__', '')
        usage = getattr(module, '__plugin_usage__', '')
        bot.plugins.add(Plugin(module, name, usage))
        module.register(bot)
        return True 
    except Exception as e:
        print(str(e))
        return False

def load_plugins(bot, plugin_dir, module_prefix):
    bot.plugins = set()
    for name in os.listdir(plugin_dir):
        path = os.path.join(plugin_dir, name)
        if os.path.isfile(path) and (name.startswith('_') or not name.endswith('.py')):
            continue
        if os.path.isdir(path) and (name.startswith('_') or not os.path.exists(os.path.join(path, '__init__.py'))):
            continue

        m = re.match(r'([_A-Z0-9a-z]+)(.py)?', name)
        if not m: continue

        load_plugin(bot, f'{module_prefix}.{m.group(1)}')
    return len(bot.plugins)

